package com.example.speaker;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.speech.tts.TextToSpeech;
import android.view.LayoutInflater;
import android.view.View;

import androidx.core.view.WindowCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.speaker.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    private String[] data = { "坐端正", "手扶好", "快点做", "快快快" };
    TextToSpeech toSpeech;
    MainActivity app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                MainActivity.this, android.R.layout.simple_list_item_1, data);
        ListView v = (ListView) findViewById(R.id.nav_host_fragment_content_main);
        v.setAdapter(adapter);


        //使用默认引擎，传入 Context 和 OnInitListener
        toSpeech = new TextToSpeech(this, this);

        final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
        final LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);

        app = this;
        v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String text= v.getItemAtPosition(i)+"";
                Toast.makeText(app, "position="+i+"text="+text,
                        Toast.LENGTH_SHORT).show();
                // String item = app.history.get(i).replaceFirst("-.*", "");
                toSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, "");
            }
        });

        v.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                final View Viewlayout = inflater.inflate(R.layout.config_dialog,
                        (ViewGroup) findViewById(R.id.layout_dialog));


                popDialog.setIcon(android.R.drawable.btn_star_big_on);
                popDialog.setTitle("Input User and Password ");
                popDialog.setView(Viewlayout);

// Button OK
                popDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){

                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

// txtUsername and Password (Dialog)
                                EditText user = (EditText) Viewlayout.findViewById(R.id.txtUsername);
                                EditText pass = (EditText) Viewlayout.findViewById(R.id.txtPassword);

// txtResult (Main Screen)
//                                TextView result = (TextView) findViewById(R.id.txtResult);
//                                result.setText(" Username : " + user.getText().toString() + " \n" +
//                                        " Password : " + pass.getText().toString() + " ");

                            }



                        })

// Button Cancel
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {
                                        dialog.cancel();
                                    }
                                });

                popDialog.create();
                popDialog.show();
                return false;
            }
        });




    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    private void changeLanguage(Locale locale) {
        int result = toSpeech.setLanguage(locale);
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Toast.makeText(app, "设置语言(" + locale.getLanguage() + ")失败：数据丢失或不支持", Toast.LENGTH_SHORT).show();
        }
        if (toSpeech != null) {
            toSpeech.setPitch(1.0f);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        }

    }

    private void changeLanguage(String lang) {
        // will set LANG, pitch, speed

        int result = toSpeech.setLanguage(new Locale(lang));    // Locale.ITALY;
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Toast.makeText(app, "设置语言(" + lang + ")失败：数据丢失或不支持", Toast.LENGTH_SHORT).show();
        }
        if (toSpeech != null) {
            toSpeech.setPitch(1.0f);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        }

    }
    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            changeLanguage(Locale.CHINESE);
        }

    }
}